<template>
    <div class="shangpin">
        <!--        全部门店,已上架和已下架-->
        <div @click="change0" :style="{color:color0}" class="topLi">{{arr[0]}}</div>
        <div @click="change1" :style="{color:color1}" class="topLi">{{arr[1]}}</div>
        <div @click="change2" :style="{color:color2}" class="topLi">{{arr[2]}}</div>
        <!--       门店搜索 -->
        <span class="from">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="门店名称:">
                <el-input v-model="formInline.name"></el-input>
            </el-form-item>
                <el-form-item label="门店手机号:">
                <el-input v-model="formInline.tel"></el-input>
            </el-form-item>
                <!--                //日期-->
                <el-form-item label="提交日期:">
                    <el-date-picker
                            v-model="value1"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <!--                //搜索日期-->
            <el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
        </el-form>
        </span>
        <!--        新增门店-->
        <div style="margin-bottom: 30px">
            <el-button type="text" @click="newData"
                       :style="{'background-color':'#409EFF',color:'#ffffff',textAlign:'center',width:'100px',padding:'10px 0'}">
                <span>新增门店</span>
            </el-button>
            <!--            新增门店-->
            <el-dialog :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="form">
                    <el-form-item label="门店名称" :label-width="formLabelWidth">
                        <el-input autocomplete="off" v-model="form.shopName"></el-input>
                    </el-form-item>
                    <el-form-item label="门店头像" :label-width="formLabelWidth">
                        <el-upload
                                class="avatar-uploader"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
                            <i v-else style="width: 35px; height: 35px" class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="门店手机号" :label-width="formLabelWidth">
                        <el-input autocomplete="off" v-model="form.shopPhone"></el-input>
                    </el-form-item>
                    <el-form-item label="所属地区" :label-width="formLabelWidth">
                        <el-cascader
                                :options="addressAll"
                                clearable
                                v-model="address"
                                :props="{value:'label'}"
                                :style="{marginBottom:'25px'}"
                        ></el-cascader>
                        <el-input v-model="form.shopAddress" autocomplete="off" placeholder="请填写详细地址"></el-input>
                    </el-form-item>
                    <el-form-item label="营业时间" :label-width="formLabelWidth">
                        <el-input autocomplete="off" v-model="form.shopDescribe"></el-input>
                    </el-form-item>
                </el-form>

                <div style="margin-left: 50px" class="cf">
                    <span style="margin-right: 15px;">门店坐标</span>
                    <el-button @click="getLocation">获取位置</el-button>
                    {{location}}
                </div>

                <!-------------------------------------------------------------------------------------------------->
                <div slot="footer" class="dialog-footer cf">
                    <el-button type="primary" @click="saveDate">保 存</el-button>
                </div>
                <!--                ---------------------------------------------------------------------------------->
            </el-dialog>
        </div>
        <!--        门店列表展示-->
        <template>
            <el-table
                    :data="tableData"
                    border
                    style="width: 100%"
                    :header-cell-style="{'background-color':'#409EFF',color:'#fff',textAlign:'center'}"
                    :cell-style="{'text-align':'center'}">
                <el-table-column
                        prop="shopName"
                        label="门店">
                </el-table-column>
                <el-table-column
                        prop="shopId"
                        label="ID">
                </el-table-column>
                <el-table-column
                        prop="shopPhone"
                        label="门店手机号">
                </el-table-column>
                <el-table-column
                        prop="shopAddress"
                        label="门店地址">
                </el-table-column>
                <el-table-column
                        prop="shopDescribe"
                        label="营业时间">
                </el-table-column>
                <el-table-column
                        label="关联小区">
                </el-table-column>
                <el-table-column
                        prop="shopOrderCount"
                        label="订单总数">
                </el-table-column>
                <el-table-column
                        label="提交方式">
                </el-table-column>
                <el-table-column
                        prop="shopStatus"
                        label="状态">
                    <span style="font-size: 12px;  color: #1890FF">上架中</span>
                </el-table-column>

                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" size="small">门店管理</el-button>
                        <el-button @click="handleClick(scope.$index)" type="text" size="small">修改门店资料</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
        <!--                显示分页组件-->
        <template>
            <el-pagination
                    @prev-click="preChange()"
                    @next-click="nextChange()"
                    @current-change="currentPageChange"
                    @size-change="currentSizeChange"
                    :current-page.sync="pageNum"
                    :page-sizes="[5,10,15,20,25,30]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next"
                    :total="MenDianCount"
                    style="margin-top: 15px"
                    background
            >
            </el-pagination>
        </template>
    </div>
</template>

<script>
    export default {
        name: "ShangPinComponent",
        data() {
            return {
                arr: ["全部门店", "上架中", "已下架"],
                color0: "#0ff",
                color1: "#000",
                color2: "#000",
                value1: '',
                boolean: "",
                title: "",
                tableData: [],
                addressAll: [],   //省市区
                address: [], //你选择的地址
                location: "",
                imageUrl: '',
                formInline: {
                    name: '',
                    tel: ''
                },
                form: {
                    shopId: '',
                    shopName: '',
                    shopPhone: "",
                    shopAddress: '',
                    shopDescribe: "",
                    shopCity: "",
                    shopDistrict: "",
                    shopStatus: "",
                },
                formLabelWidth: '120px',
                dialogFormVisible: false,
                //页面的总条数
                MenDianCount: 0,
                //页面显示条数
                pageSize: 5,
                //当前页
                pageNum: 1,
                //每页可以显示的几条
                pageShowSize: [5, 10, 15, 20, 50, 100]
            }
        },
        created() {
            this.refresh();
            this.getAllProvinceAndCityList();
        },
        methods: {
            change0() {
                this.color0 = "#0ff"
                this.color1 = "#000"
                this.color2 = "#000"
            },
            change1() {
                this.color1 = "#0ff"
                this.color0 = "#000"
                this.color2 = "#000"
            },
            change2() {
                this.color2 = "#0ff"
                this.color1 = "#000"
                this.color0 = "#000"
            },
            //刷新,获取整个页面数据
            refresh() {
                this.axios.get("/MenDian/DataList", {
                    params: {
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                    }
                }).then((res) => {
                        this.tableData = res.data.list;
                        this.MenDianCount = res.data.MenDianCount;
                    }
                ).catch((error) => {
                    console.log(error)
                });
            },
            //点击新增门店执行的操作
            newData() {
                this.boolean = true;
                this.title = '新增门店';
                this.dialogFormVisible = true;
                //清除编辑门店是显示的数据
                this.clearMenDianData();
            },
            //搜索日期
            onSubmit() {
                // 当日期等于空的时候走的路线
                if (this.value1 == "") {
                    console.log(this.pageNum);
                    console.log(this.pageSize);
                    this.axios.get("/MenDian/query", {
                        params: {
                            pageNum: this.pageNum,
                            pageSize: this.pageNum,
                            phone: this.formInline.tel,
                            name: this.formInline.name,
                            startTime: "",
                            endTime: "",
                            shopStatus: this.form.shopStatus,
                        }
                    }).then(res => {
                        //传递查询到的数据
                        this.tableData = res.data.list;
                    }).catch(error => {
                        console.log(error)
                    })
                } else {
                    //当日期不为空的时候走的路线
                    this.axios.get("/MenDian/query", {
                        params: {
                            pageNum: this.pageNum,
                            pageSize: this.pageNum,
                            phone: this.formInline.tel,
                            name: this.formInline.name,
                            startTime: this.getDateString(this.value1[0]),
                            endTime: this.getDateString(this.value1[1]),
                            shopStatus: this.form.shopStatus,
                        }
                    }).then(res => {
                        this.tableData = res.data.list;
                    }).catch((error) => {
                        console.log(error)
                    });
                }
            },
            //保存数据
            saveDate() {
                //是否重用一个弹框
                this.dialogFormVisible = false;
                //boolean如果是true就是添加，false就是修改
                if (this.boolean) {
                    this.addData();
                } else {
                    this.changeData();
                }
            },
            //新增门店
            addData() {
                this.axios.post("/MenDian/add", {
                    shopAddress: this.form.shopAddress,
                    shopCity: this.address[1],
                    shopDescribe: this.form.shopDescribe,
                    shopDistrict: this.address[2],
                    shopImage: this.imageUrl,
                    shopLatitude: this.location.split(",")[0],
                    shopLongitude: this.location.split(",")[1],
                    shopName: this.form.shopName,
                    shopPhone: this.form.shopPhone,
                    shopProvince: this.address[0],
                }).then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            type: "success",
                            message: res.data.message,
                            showClose: true
                        })
                        //添加成功后重新刷新页面数据数据
                        setTimeout(this.refresh, 500);
                    } else {
                        this.$message({
                            type: "error",
                            message: res.data.message,
                        })
                    }
                }).catch((error) => {
                    console.log(error)
                });
            },
            //修改门店数据赋值
            handleClick(index) {
                this.boolean = false;
                this.dialogFormVisible = true;
                this.title = '编辑门店';
                //显示编辑门店信息
                this.showMenDianAgainData(index);
            },
            //修改门店数据
            changeData() {
                this.axios.post("/MenDian/update", {
                    shopAddress: this.form.shopAddress,
                    shopCity: this.address[1],
                    shopDescribe: this.form.shopDescribe,
                    shopDistrict: this.address[2],
                    shopImage: this.imageUrl,
                    shopLatitude: this.location.split(",")[0],
                    shopLongitude: this.location.split(",")[1],
                    shopName: this.form.shopName,
                    shopPhone: this.form.shopPhone,
                    shopProvince: this.address[0],
                    shopId: this.form.shopId,
                }).then((res) => {
                    if (res.data.code === 200) {
                        this.$message({
                            type: "success",
                            message: res.data.message,
                            showClose: true
                        })
                        //修改成功后重新刷新页面数据数据
                        setTimeout(this.refresh, 500);
                    } else {
                        this.$message({
                            type: "error",
                            message: res.data.message,
                        })
                    }
                }).catch((error) => {
                    console.log(error);
                });
            },
            //添加图片
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //获取省市
            getAllProvinceAndCityList() {
                // 获取全国所有省份和城市的列表
                var that = this;
                this.$http
                    .get("https://restapi.amap.com/v3/config/district", {
                        // 高德地图的API
                        params: {
                            key: "39444c57178c072ed26912eab8a9f3d6", // 这个是申请的 Key，读者自行写入
                            keywords: "中国",
                            subdistrict: 3,
                            extensions: "base",
                        },
                    })
                    .then((response) => {
                        // console.log(response.data)
                        for (let i = 0; i < response.data.districts[0].districts.length; i++) {
                            let provinceMap = new Map();
                            provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
                            provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
                            provinceMap.children = [];
                            that.addressAll.push(provinceMap);  //添加省份
                            for (let j = 0; j < response.data.districts[0].districts[i].districts.length; j++) {
                                let cityMap = new Map()
                                cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
                                cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
                                cityMap.children = [];
                                provinceMap.children.push(cityMap); //添加市
                                for (let k = 0; k < response.data.districts[0].districts[i].districts[j].districts.length; k++) {
                                    let areaMap = new Map()
                                    areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                                    areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                                    cityMap.children.push(areaMap);   //添加区县
                                }
                            }
                        }
                    });
            },
            //获取坐标
            getLocation() {
                this.axios.get("https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=" + this.address.join("") + this.detail).then((loc) => {
                    // console.log(loc);
                    this.location = loc.data.geocodes[0].location;
                    // console.log(this.location)
                }).catch(() => {
                })
            },
            //封装日期转为字符串的函数
            getDateString(date) {
                let yy = date.getFullYear();
                let mm = date.getMonth() + 1;
                let dd = date.getDate();
                // let hh = date.getHours();
                // let mf = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
                // let ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                let str = yy + "-" + mm + "-" + dd;
                return str;
            },
            //添加之前的清空数据
            clearMenDianData() {
                this.form.shopAddress = "";
                this.form.shopDescribe = "";
                this.form.shopDistrict = "";
                this.imageUrl = "";
                this.location = "";
                this.form.shopName = "";
                this.form.shopPhone = "";
                this.address = "";
            },
            //数据回显，点击编辑按钮时，调出本行数据
            showMenDianAgainData(index) {
                this.form.shopName = this.tableData[index].shopName;
                this.form.shopDescribe = this.tableData[index].shopDescribe;
                this.imageUrl = this.tableData[index].shopImage;
                this.form.shopPhone = this.tableData[index].shopPhone;
                this.form.shopAddress = this.tableData[index].shopAddress;
                this.address = (this.tableData[index].shopProvince + "," + this.tableData[index].shopCity + "," + this.tableData[index].shopDistrict).split(",")
                this.address[2] = this.tableData[index].shopDistrict;
                this.form.shopId = this.tableData[index].shopId;
                this.address[0] = this.tableData[index].shopProvince;
                this.location = this.tableData[index].shopLongitude + "," + this.tableData[index].shopLatitude;
            },
            //点击分页组件的上一页
            preChange() {
                if (this.pageNum <= 0) {
                    this.pageNum = 0;
                    this.refresh();
                } else {
                    this.pageNum = this.pageNum - 1;
                    this.refresh();
                }
            },
            //点击分页分组的下一页
            nextChange() {
                this.pageNum = this.pageNum + 1;
                this.refresh();

            },
            // 点击任意页数
            currentPageChange() {
                this.refresh();
            },
            //点击size获取里卖的个数
            currentSizeChange(val) {
                this.pageSize = val;
                this.refresh();
            },
        }
    }
</script>

<style scoped>
    .shangpin {
        padding: 20px;
    }

    .topLi {
        display: inline;
        padding: 0 15px;
    }

    .topLi:first-of-type {
        color: #00ffff;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 35px;
        height: 35px;
        line-height: 35px;
        text-align: center;
    }

    .avatar {
        width: 35px;
        height: 35px;
        display: block;
    }
</style>